package top.yokey.android.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;

import top.yokey.android.R;
import top.yokey.android.activity.DynamicAddActivity;
import top.yokey.android.adapter.CircleAdapter;
import top.yokey.android.http.BaseCallBack;
import top.yokey.android.http.CircleBean;
import top.yokey.android.http.HttpHelp;

public class HomeFragment extends Fragment {

    private ArrayList<CircleBean> arrayList = new ArrayList<>();
    private CircleAdapter adapter = new CircleAdapter(arrayList);

    private AppCompatImageView addImageView;
    private RecyclerView mainRecyclerView;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        addImageView = root.findViewById(R.id.addImageView);
        mainRecyclerView = root.findViewById(R.id.mainRecyclerView);

        //设置布局管理器
        mainRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //将适配器与RecyclerView绑定
        mainRecyclerView.setAdapter(adapter);

        initEvent();
        getList();
        return root;
    }

    private void initEvent() {

        addImageView.setOnClickListener(view -> startActivity(new Intent(getActivity(), DynamicAddActivity.class)));

    }

    //自定义方法

    private void getList() {

        HttpHelp.get().ready("circle", "getList")
                .add("page", "1")
                .get(new BaseCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        //将json数组 通过遍历json对象的形式 转换为 json对象
                        try {
                            JSONArray jsonArray = new JSONArray(data);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                arrayList.add(new Gson().fromJson(jsonArray.getString(i), CircleBean.class));
                            }
                            adapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(String reason) {

                    }
                });

    }

}
